from sqlalchemy import Column, String, inspect, Integer
from service.database import Base, SessionLocal


# 定义一个 User 模型
class User(Base):
    __tablename__ = "user"
    username = Column(String, primary_key=True, index=True)
    password = Column(String)
    gender = Column(Integer)
    age = Column(Integer)
    email = Column(String)
    name = Column(String)

    def todict(self):
        result = {}
        for c in inspect(self).mapper.column_attrs:
            value = getattr(self, c.key)
            if value is not None:
                result[c.key] = str(value)
        return result

    def from_dict(self, data: dict):
        for field in ['username', 'password', 'gender', 'age', 'email', 'name']:
            if field in data and data[field] is not None:
                setattr(self, field, data[field])


def create_user(username: str, password: str) -> bool:
    db = SessionLocal()
    try:
        user = get_user(username)
        if user:
            return False
        user = User(username=username, password=password)
        db.add(user)
        db.commit()
        return True
    finally:
        db.close()


def get_user(username: str):
    db = SessionLocal()
    try:
        return db.query(User).filter(User.username == username).first()
    finally:
        db.close()


def delete_user(username: str) -> bool:
    db = SessionLocal()
    try:
        user = get_user(username)
        if user:
            db.delete(user)
            db.commit()
            return True
        else:
            return False
    finally:
        db.close()


def update_user(user_data: dict) -> bool:
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.username == user_data['username']).first()
        # 更新用户信息
        if user:
            for key, value in user_data.items():
                if isinstance(value, str) and len(value.strip()) == 0:
                    continue
                if value is None:
                    continue
                setattr(user, key, value)
            db.commit()
            return True
        else:
            return False
    finally:
        db.close()
